package net.citrite.android;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

/**
 * Created by taodongl on 5/14/2015.
 */
public class XmlNodeReport {
    public static void parse(File file, List<Position> positionList) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            //factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
            String xmlText = Files.toString(file, Charsets.UTF_8);
            parser.setInput(new StringReader(xmlText));
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG: {
                        int line = parser.getLineNumber();
                        //System.out.println("begin-> node: " + tagName + "line: " + line);
                        updatePosition(line, tagName, positionList);
                        break;
                    }
//                    case XmlPullParser.END_TAG: {
//                        int line = parser.getLineNumber();
//                        System.out.println("end-> node: " + tagName + "line: " + line);
//                        break;
//                    }
                }
                eventType = parser.next();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
    }

    private static void updatePosition(int pos, String name, List<Position> positionList) {
        if (pos <= 0 || name == null || name.isEmpty()) {
            return;
        }
        for (Position position : positionList) {
            if (position.getEndPos() == pos && position.getLabel().equals(name)) {
                return;
            }
        }
        Position position = new Position(pos, name);
        if (!positionList.isEmpty()) {
            position.setStartPos(positionList.get(positionList.size() - 1).getEndPos());
        }
        positionList.add(position);
    }
}
